package cn.jekun.web.agent.action;

import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import cn.jekun.component.base.bean.ErrorMsg;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.DCity;
import cn.jekun.component.core.bean.gen.DProvince;
import cn.jekun.component.core.bean.gen.DRegion;
import cn.jekun.component.core.bean.gen.ErpShop;
import cn.jekun.component.core.bean.gen.RsAgent;
import cn.jekun.component.core.service.gen.ErpShopService;
import cn.jekun.component.core.service.gen.RsAgentService;
import cn.jekun.web.agent.bean.Agent;
import cn.jekun.web.agent.service.WebAgentService;
import cn.jekun.web.shop.bean.Shop;
import cn.jekun.web.shop.service.ShopService;

/**
 * 代理商管理
 * 
 * @author twj
 * 
 */
@SuppressWarnings("serial")
public class AgentAction extends AgentBaseAction {
	private RsAgent agent;
	private String agentId;
	private String shopId;
	private String shopName;
	private String provinceId;
	private String cityId;
	private String regionId;
	private List<ErpShop> list = new ArrayList<ErpShop>();

	public RsAgent getAgent() {
		return agent;
	}

	public void setAgent(RsAgent agent) {
		this.agent = agent;
	}

	public String getAgentId() {
		return agentId;
	}

	public void setAgentId(String agentId) {
		this.agentId = agentId;
	}

	public String getShopId() {
		return shopId;
	}

	public void setShopId(String shopId) {
		this.shopId = shopId;
	}

	public String getShopName() {
		return shopName;
	}

	public void setShopName(String shopName) {
		this.shopName = shopName;
	}

	public List<ErpShop> getList() {
		return list;
	}

	public void setList(List<ErpShop> list) {
		this.list = list;
	}

	public String getProvinceId() {
		return provinceId;
	}

	public void setProvinceId(String provinceId) {
		this.provinceId = provinceId;
	}

	public String getCityId() {
		return cityId;
	}

	public void setCityId(String cityId) {
		this.cityId = cityId;
	}

	public String getRegionId() {
		return regionId;
	}

	public void setRegionId(String regionId) {
		this.regionId = regionId;
	}

	@Resource(name = RsAgentService.BEAN_NAME)
	RsAgentService rsAgentService;
	@Resource(name = ErpShopService.BEAN_NAME)
	ErpShopService erpShopService;
	@Resource(name = ShopService.BEAN_NAME)
	ShopService shopService;
	
	@Resource(name = WebAgentService.BEAN_NAME)
	WebAgentService webAgentService;
	/**
	 * 查询agentId的代理商信息
	 */
	
	public String aaa(){
		System.out.println("==============================================test======================================");
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public String queryAgent() {
		JSONObject jsonObject = new JSONObject();
		//检测是否拥有 权限
		boolean EDIT = this.coreAuthService.checkRigth(this.getSessionUser().getUserId(), "AGENT_MY_INFO_MANAGER");
		
		//是否出现按钮
		jsonObject.put("EDIT",EDIT) ;
		
		
		try {
//			formMap.put(RsAgent.COL_AGENT_ID, this.getSessionUser().getAgentId());
//			SqlUtis.prepareSql(formMap, SqlUtis.getSQL(formMap, "a." + RsAgent.COL_AGENT_ID, Types.VARCHAR, SqlUtis.EQ));
			   
			//agent = this.rsAgentService.one(formMap);
			String agentId = this.getSessionUser().getAgentId();
//			agent = this.rsAgentService.one(formMap);
			Agent tempagent = this.webAgentService.getRsAgent(agentId);
			jsonObject.element("ADDRESS", tempagent.getAddress() == null ? "" : tempagent.getAddress());
			jsonObject.element("AGENT_ID", tempagent.getAgentId() == null ? "" : tempagent.getAgentId());
			jsonObject.element("AGENT_NAME", tempagent.getAgentName() == null ? "" : tempagent.getAgentName());
			jsonObject.element("AGENT_TYPE", tempagent.getAgentType() == null ? "" : tempagent.getAgentType());
			jsonObject.element("CONTACT", tempagent.getContact() == null ? "" : tempagent.getContact());
			jsonObject.element("CONTACT_NAME", tempagent.getContactName() == null ? "" : tempagent.getContactName());
			jsonObject.element("CREATE_TIME", tempagent.getCreateName() == null ? "" : tempagent.getCreateTime());
			jsonObject.element("MEMO", tempagent.getMemo() == null ? "" : tempagent.getMemo());
			jsonObject.element("MOBILE", tempagent.getMobile() == null ? "" : tempagent.getMobile());
			jsonObject.element("PARENT_AGENT_ID", tempagent.getParentAgentId() == null ? "" : tempagent.getParentAgentId());
//			jsonObject.element("PROVINCE_ID", tempagent.getProvinceId() == null ? "" : tempagent.getProvinceId());
//			jsonObject.element("CITY_ID", tempagent.getCityId() == null ? "" : tempagent.getCityId());
//			jsonObject.element("REGION_ID", tempagent.getRegionId() == null ? "" : tempagent.getRegionId());
			jsonObject.element("PROVINCE_NAME", tempagent.getProviceName() == null ? "" : tempagent.getProviceName());
			jsonObject.element("CITY_NAME", tempagent.getCityName() == null ? "" : tempagent.getCityName());
			jsonObject.element("REGION_NAME", tempagent.getRegionName() == null ? "" : tempagent.getRegionName());
			jsonObject.element(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			jsonObject.element(ErrorMsg.KEY_MESSAGE, "调用成功");
		} catch (Exception e) {
			e.printStackTrace();
			jsonObject.element(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			jsonObject.element(ErrorMsg.KEY_MESSAGE, ErrorMsg.CALL_FAIL);
		}
		return this.writeJson(jsonObject);
		// return "/agent/agentDetail.jsp";
	}

	/**
	 * 加载数据
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String loadAgent() {
		JSONObject jsonObject = new JSONObject();
		formMap.put(RsAgent.COL_AGENT_ID, this.getSessionUser().getAgentId());
		SqlUtis.prepareSql(formMap, SqlUtis.getSQL(formMap, "a." + RsAgent.COL_AGENT_ID, Types.VARCHAR, SqlUtis.EQ));
		agent = this.webAgentService.getRsAgent(this.getSessionUser().getAgentId());
		return "/agent/agentInfo.jsp";
	}

	/**
	 * 保存修改信息
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String saveAgent() {
		JSONObject jsonObject = new JSONObject();
//		formMap.put("rsAgent", agent);
//		formMap.put(RsAgent.COL_AGENT_ID, this.getSessionUser().getAgentId());
//		SqlUtis.prepareSql(formMap, SqlUtis.getSQL(formMap, "a." + RsAgent.COL_AGENT_ID, Types.VARCHAR, SqlUtis.EQ));
		String tempAgentId = this.getSessionUser().getAgentId(); //获取代理商的代码
		boolean exists = this.webAgentService.exists(this.getSessionUser().getAgentId());
		if (!exists) {
            jsonObject.element(ErrorMsg.KEY_CODE,ErrorMsg.CALL_FAIL);	
            jsonObject.element(ErrorMsg.KEY_MESSAGE, "此代理商不存在");
			this.saveActionError("此代理商不存在");
//			return "!/agent/Agent/queryAgent.do";
			return this.writeJson(jsonObject);
		}
        RsAgent rsAgent = this.webAgentService.getRsAgent(tempAgentId); //根据agentId获取代理商
	    String tempAgentName = rsAgent.getAgentName();
        String agentName = agent.getAgentName();
        if(!agentName.equals(tempAgentName)){
		exists = this.webAgentService.existsByAgentName(agentName);
		if(exists){
			 jsonObject.element(ErrorMsg.KEY_CODE,ErrorMsg.CALL_FAIL);	
	         jsonObject.element(ErrorMsg.KEY_MESSAGE, "此代理商名称已存在：" + agentName);
		     this.saveActionError("此代理商名称已存在。");
		     return this.writeJson(jsonObject);
		}
        }
//		this.rsAgentService.update(formMap);
		this.webAgentService.updateAgent(agent,this.getSessionUser().getAgentId());
		this.logService.addAgentAuditLog("", "用户：" + this.getSessionUser().getUserName() + "修改了" + this.getSessionUser().getAgentName() + "代理商信息");// 记录操作日志
		this.getSessionUser().setAgentName(agent.getAgentName());
		jsonObject.element(ErrorMsg.KEY_CODE,ErrorMsg.CALL_OK);	
        jsonObject.element(ErrorMsg.KEY_MESSAGE, "修改成功");
		//		return "!/agent/Agent/queryAgent.do";
	    return this.writeJson(jsonObject);
	}

	/**
	 * 查询代理商所拥有的商家
	 */
	@SuppressWarnings("unchecked")
	public String queryShopsByAgentId() {
		JSONObject jsonObject = new JSONObject();
		JSONArray jsonArray = new JSONArray();
		String tempAgentId = this.getSessionUser().getAgentId();
//		formMap.put(ErpShop.COL_AGENT_ID, tempAgentId);
//		formMap.put(ErpShop.COL_SHOP_ID, shopId);
//		formMap.put(ErpShop.COL_SHOP_NAME, shopName);
//		SqlUtis.prepareSql(formMap, SqlUtis.getSQL(formMap, "a." + ErpShop.COL_AGENT_ID, Types.VARCHAR, SqlUtis.EQ), SqlUtis.getSQL(formMap, "a." + ErpShop.COL_SHOP_ID, Types.VARCHAR, SqlUtis.EQ),
//				SqlUtis.getSQL(formMap, "a." + ErpShop.COL_SHOP_NAME, Types.VARCHAR, SqlUtis.LIKE));
		try{
//		this.resultList = this.erpShopService.list(formMap, page);
		this.resultList = this.webAgentService.getErpShopList(tempAgentId,shopId,shopName,page);
		
		for(int i =0,length = resultList.size();i < length; i++){
	    	Agent shop =(Agent)resultList.get(i);
	    	Map  hashMap = new HashMap();
	    	hashMap.put("shopId",shop.getShopId() == null?"":shop.getShopId());
	    	hashMap.put("shopName",shop.getShopName()==null?"":shop.getShopName());
	    	hashMap.put("mobile",shop.getMobile()==null?"":shop.getMobile());
	    	hashMap.put("merchantName",shop.getMerchantName() ==null?"":shop.getMerchantName()); 
	    	hashMap.put("merchantNo", shop.getMerchantNo() ==null?"":shop.getMerchantNo());
	    	hashMap.put("bindUserCount", shop.getBindUserCount() ==null?"":shop.getBindUserCount());
	    	hashMap.put("noBindUserCount", shop.getNoBindUserCount() ==null?"":shop.getNoBindUserCount());
	    	hashMap.put("createTime",shop.getCreateTime() == null?"":DateToDString(shop.getCreateTime()));
	    	jsonArray.add(hashMap); //添加
	    }
		jsonObject.element("resultList",jsonArray);  //将查找的结果返回
		jsonObject.element(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
		jsonObject.element(ErrorMsg.KEY_MESSAGE, "成功调用");
		jsonObject.put(Constants.Page.PAGE_NUMBER,page.getPageNumber());
		jsonObject.put(Constants.Page.PAGE_SIZE,page.getPageSize());
		jsonObject.put(Constants.Page.TOTAL_COUNT,page.getTotalCount());
		jsonObject.put(Constants.Page.TOTAL_PAGE,page.getPages());
		}catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
		    jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
		}
		return this.writeJson(jsonObject);
	}

//	/**
//	 * 终端设备监控
//	 * 
//	 * @return
//	 */
//	@SuppressWarnings("unchecked")
//	public String queryTerminalByAgentId() {
//		JSONObject jsonObject = new JSONObject();
//		JSONArray jsonArray = new JSONArray();
//	    String tempAgentId = this.getSessionUser().getAgentId();
////		formMap.put(RsTerminal.COL_SHOP_ID, shopId);
////		formMap.put(ErpShop.COL_SHOP_NAME, shopName);
//
//		/*
//		 * SqlUtis.getSQL(formMap, "a." + RsAgent.COL_AGENT_ID, Types.VARCHAR,
//		 * SqlUtis.EQ),
//		 */
//
////		SqlUtis.prepareSql(formMap,SqlUtis.getSQL(formMap, "a." + RsTerminal.COL_SHOP_ID, Types.VARCHAR, SqlUtis.EQ),
////				SqlUtis.getSQL(formMap, "s." + ErpShop.COL_SHOP_NAME, Types.VARCHAR, SqlUtis.LIKE));
//	    try{
////		this.resultList = this.shopTerminalService.list(formMap, page);
////	    	this.resultList = this.shopTerminalService.list(shopId, shopName,page);
//	    this.resultList = this.shopTerminalService.queryTerminallListByAgentId(tempAgentId, shopId,shopName, page);
//	    System.out.println("終端長度 ="+resultList.size());
//	    
//		jsonObject.put("resultList", resultList);
//		for(int i =0,length = resultList.size();i<length;i++){
//			Terminal terminal = (Terminal)resultList.get(i);//获取终端
//		    Map map = new HashMap();
//		    map.put("terminalId", terminal.getTerminalId()==null?"":terminal.getTerminalId()); //终端代码
//		    map.put("shopId", terminal.getShopId()==null?"":terminal.getShopId()); //商户代码
//		    map.put("shopName", terminal.getShopName()==null?"":terminal.getShopName()); //商户名称
//		    map.put("agentName", terminal.getAgentName()==null?"":terminal.getAgentName()); //代理商名称
//		    map.put("vendorName", terminal.getVendorName()==null?"":terminal.getVendorName()); //生产厂家名称
//		    map.put("version", terminal.getVersion()==null?"":terminal.getVersion());
//		    map.put("available",(terminal.getAvailable() == null || !terminal.getAvailable().equals("1"))?"无效":"有效"); //是否有效
//		    map.put("total", terminal.getTotal()==null?"离线":"在线");
//		    jsonArray.add(map);
//		}
//		jsonObject.put("resultList", jsonArray);
//		jsonObject.element(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
//		jsonObject.element(ErrorMsg.KEY_MESSAGE, "成功调用");
//		jsonObject.put(Constants.Page.PAGE_NUMBER,page.getPageNumber());
//		jsonObject.put(Constants.Page.PAGE_SIZE,page.getPageSize());
//		jsonObject.put(Constants.Page.TOTAL_COUNT,page.getTotalCount());
//		jsonObject.put(Constants.Page.TOTAL_PAGE,page.getPages());
//	    }catch (BusinessException e) {
//			jsonObject = JSONObject.fromObject(e.getErrorMsg());
//		} catch (Exception e) {
//		    jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
//		}
//		return this.writeJson(jsonObject);
//	}

	/**
	 * 终端设备监控(地图)
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String queryTerminalMapByAgentId() {
		JSONObject  jsonObject = new JSONObject();
		formMap.put(RsAgent.COL_AGENT_ID, this.getSessionUser().getAgentId());
		String agentId = this.getSessionUser().getAgentId();
		formMap.put(ErpShop.COL_SHOP_NAME, shopName);
		formMap.put(DProvince.COL_PROVINCE_ID, provinceId);
		formMap.put(DCity.COL_CITY_ID, cityId);
		formMap.put(DRegion.COL_REGION_ID, regionId);
		SqlUtis.prepareSql(formMap, SqlUtis.getSQL(formMap, "a." + RsAgent.COL_AGENT_ID, Types.VARCHAR, SqlUtis.EQ),
				SqlUtis.getSQL(formMap, "a." + DProvince.COL_PROVINCE_ID, Types.VARCHAR, SqlUtis.EQ), 
				SqlUtis.getSQL(formMap, "a." + DCity.COL_CITY_ID, Types.VARCHAR, SqlUtis.EQ),
				SqlUtis.getSQL(formMap, "a." + DRegion.COL_REGION_ID, Types.VARCHAR, SqlUtis.EQ), 
				SqlUtis.getSQL(formMap, "a." + ErpShop.COL_SHOP_NAME, Types.VARCHAR, SqlUtis.LIKE));
		try{
//		this.resultList = this.erpShopService.list(formMap, page);
		this.resultList = this.webAgentService.getErpShopList(agentId, shopName, provinceId,cityId,regionId,page);
//		this.erpShopService.one(map);
		jsonObject.element("resultList", resultList);
		jsonObject.element(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
		jsonObject.element(ErrorMsg.KEY_MESSAGE, "成功调用");
		jsonObject.put(Constants.Page.PAGE_NUMBER,page.getPageNumber());
		jsonObject.put(Constants.Page.PAGE_SIZE,page.getPageSize());
		jsonObject.put(Constants.Page.TOTAL_COUNT,page.getTotalCount());
		jsonObject.put(Constants.Page.TOTAL_PAGE,page.getPages());
		System.out.println("jsonObject = "+jsonObject);
		}catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
			return this.writeJson(jsonObject);
		}
		return this.writeJson(jsonObject);
//		return "/agent/agentTerminalMap.jsp";
	}
	
	
//	@SuppressWarnings("unchecked")
//	public String queryTerminalsByShopId() {
//		String erpShopId = this.request.getParameter("erpShopId");
//		
////		List<String> list = this.rsTerminalService.listBySql("select a.terminal_id from rs_terminal a where a.shop_id='" + erpShopId + "'");
//		List<String> list = this.webAgentService.queryTerminalsByShopId(erpShopId);
//		JSONArray json = JSONArray.fromObject(list);
//		return this.writeJson(json);
//	}

	/**
	 * 根据shopId查找商店的详情
	 * @return
	 */
	public String getShopDetailByShopId(){
		JSONObject jsonObject = new JSONObject();
		JSONArray jsonArray = new JSONArray();
		Map map  = null;
		try{
			formMap.put(ErpShop.COL_SHOP_ID,shopId);
			SqlUtis.prepareSql(formMap,SqlUtis.getSQL(formMap, "a." + ErpShop.COL_SHOP_ID, Types.VARCHAR, SqlUtis.EQ));
//			Shop tempshop = this.shopService.one(formMap);
			Shop tempshop = this.shopService.getShopDetial(shopId);
            if(tempshop != null){
            	jsonObject.put(Shop.COL_SHOP_ID, tempshop.getShopId()==null?"":tempshop.getShopId());
    			
    			jsonObject.put(Shop.COL_LOGO_URL, tempshop.getLogoUrl()==null?"":tempshop.getLogoUrl());
    			
    			jsonObject.put(Shop.COL_SHOP_TYPE_ID, tempshop.getShopTypeId()==null?"":tempshop.getShopTypeId());
    			jsonObject.put("SHOP_TYPE_NAME", tempshop.getShopTypeName()==null?"":tempshop.getShopTypeName());
    			
    			jsonObject.put(Shop.COL_COM_NAME, tempshop.getComName()==null?"":tempshop.getComName());

    			jsonObject.put(Shop.COL_SHOP_ID, tempshop.getShopId()==null?"":tempshop.getShopId());
    			jsonObject.put(Shop.COL_SHOP_NAME, tempshop.getShopName()==null?"":tempshop.getShopName());
    			
    			jsonObject.put(Shop.COL_AGENT_ID, tempshop.getAgentId()==null?"":tempshop.getAgentId());
    			jsonObject.put("AGENT_NAME", tempshop.getAgentName()==null?"":tempshop.getAgentName());
    			
    			jsonObject.put(Shop.COL_PROVINCE_ID, tempshop.getProvinceId()==null?"":tempshop.getProvinceId());
    			jsonObject.put("PROVINCE_NAME", tempshop.getProvinceName()==null?"":tempshop.getProvinceName());
    			
    			jsonObject.put(Shop.COL_CITY_ID, tempshop.getCityId()==null?"":tempshop.getCityId());
    			jsonObject.put("CITY_NAME", tempshop.getCityName()==null?"":tempshop.getCityName());
    			
    			jsonObject.put(Shop.COL_REGION_ID, tempshop.getRegionId()==null?"":tempshop.getRegionId());
    			jsonObject.put("REGION_NAME", tempshop.getRegionName()==null?"":tempshop.getRegionName());
    			
    			jsonObject.put(Shop.COL_STREET, tempshop.getStreet()==null?"":tempshop.getStreet());
    			
    			jsonObject.put(Shop.COL_ADDRESS, tempshop.getAddress()==null?"":tempshop.getAddress());
    			
    			jsonObject.put(Shop.COL_CONTACT, tempshop.getContact()==null?"":tempshop.getContact());
    			
    			jsonObject.put(Shop.COL_MOBILE, tempshop.getMobile()==null?"":tempshop.getMobile());
    			
    			jsonObject.put(Shop.COL_PHONE, tempshop.getPhone()==null?"":tempshop.getPhone());
    			
    			jsonObject.put(Shop.COL_BUSINESS_HOURS, tempshop.getBusinessHours()==null?"":tempshop.getBusinessHours());
    			
    			jsonObject.put(Shop.COL_MIN_AMOUNT, tempshop.getMinAmount()==null?"":tempshop.getMinAmount());
    			
    			jsonObject.put(Shop.COL_RANGE, tempshop.getRange()==null?"":tempshop.getRange());
    			
    			jsonObject.put(Shop.COL_SHIP_TIME, tempshop.getShipTime()==null?"":tempshop.getShipTime());
    			
    			jsonObject.put(Shop.COL_LATITUDE, tempshop.getLatitude()==null?"":tempshop.getLatitude());
    			
    			jsonObject.put(Shop.COL_LONGITUDE, tempshop.getLongitude()==null?"":tempshop.getLongitude());
    			
    			jsonObject.put("MCC", tempshop.getMcc()==null?"":tempshop.getMcc());
    			
    			jsonObject.put(Shop.COL_MEMO, tempshop.getMemo()==null?"":tempshop.getMemo());
    			
            }
		   jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
		   jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");
		}catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}

		return this.writeJson(jsonObject);
	}
}
